package com.ruoyi.ai.factory.impl;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.auth.Auth;
import com.baidubce.qianfan.core.builder.ChatBuilder;
import com.ruoyi.ai.domain.vo.WxChatVo;
import com.ruoyi.ai.domain.vo.WxModelConfigVo;
import com.ruoyi.ai.enums.MfgEnum;
import com.ruoyi.ai.factory.ModelChatTemplate;
import com.ruoyi.ai.ws.ChatWebSocketManager;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class QFanModelChatService extends ModelChatTemplate {
    private Qianfan qianfan;

    @Resource
    private ChatWebSocketManager chatWebSocketManager;

    public QFanModelChatService() {
        super(MfgEnum.QFAN.getType());
    }

    @Override
    public String chatStream(List<WxChatVo> chatVoList, Long userId) {
        try {
            log.info("发送的请求为{}", chatVoList);
            // 结果拼接对象
            StringBuilder resultBuilder = new StringBuilder();
            ChatBuilder chatBuilder = getChatBuilderBase();
            for (WxChatVo wxChatVo : chatVoList) {
                chatBuilder.addMessage(wxChatVo.getRole(), wxChatVo.getContent());
            }
            chatBuilder.executeStream() // 发起流式请求
                .forEachRemaining(chunk -> {
                    StringBuilder finalResBuilder = resultBuilder.append(chunk.getResult());
                    //据说代码块不终止
                    // 通过websocket返回给前端
                    //chatWebSocketManager.sendOneMessage(userId, finalResBuilder.toString());
                    chatWebSocketManager.sendOneMessage(userId, chunk.getResult());
                }); // 流式迭代，并打印消息
            //将最终结果返回
            //发送对话结束标记，前端好判断本次对话已结束，允许下一轮对话
            chatWebSocketManager.sendOneMessage(userId, OVER_FLAG);
            return resultBuilder.toString();
        } catch (Exception e) {
            log.error("调用百度接口出现问题：{}", e.getMessage());
            throw new ServiceException("调用百度接口出现问题");
        }
    }

    public ChatBuilder getChatBuilderBase() {
        WxModelConfigVo config = getConfig();
        if (config == null) {
            throw new ServiceException("模型参数未配置");
        }
        if (qianfan == null) {
            qianfan = new Qianfan(Auth.TYPE_OAUTH, config.getApiKey(), config.getSecretKey());
        }
        ChatBuilder chatBuilder = qianfan.chatCompletion();
        chatBuilder.model(config.getModelType());
        return chatBuilder;
    }
}
